﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Secams.model;
using Secams.form;
using Secams.controller;

namespace Secams
{
    public partial class MainForm : Form
    {
        protected const string DEBUG_ROOT_DIR = "../..";
        protected const string SCENARIO_FILE = "scenario-collections.xml";

        protected ScenariosCollection _scenarioCollection = new ScenariosCollection();

        // The form that displays the events & alerts
        protected List<Form> _formEventsList = new List<Form>();

        protected Trials _trials = new Trials();

        ParticipantDao _participantDao = null;

        public MainForm()
        {
#if DEBUG
            AppContext.getInstance().init(DEBUG_ROOT_DIR, DEBUG_ROOT_DIR, "/app-settings.xml");
#else
            // Application.CommonAppDataPath
            // Application.UserAppDataPath
            // Application.LocalUserAppDataPath
            AppContext.getInstance().init(Application.StartupPath, Application.StartupPath, "/app-settings.xml");
#endif
            this.Font = AppContext.getDefaultFont(this.Font);
            InitializeComponent();
            this.Text = this.Text + " " + AppContext.VERSION;
            this.WindowState = FormWindowState.Maximized;
            
#if DEBUG
            /*MessageBox.Show(this, AppContext.getInstance().startupPath 
                + ", " + AppContext.getInstance().instructionDirPath
                + ", CommonAppDataPath=" + Application.CommonAppDataPath
                + ", LocalUserAppDataPath=" + Application.LocalUserAppDataPath
                + ", UserAppDataPath=" + Application.UserAppDataPath
                , "Confirmation"); */
#endif
            _participantDao = new ParticipantDao(AppContext.getInstance().dbFilePath);
            try
            {
                _scenarioCollection.loadCollection(AppContext.getInstance().getScenarioFilePath(SCENARIO_FILE));
            }
            catch (Exception e)
            {
                MessageBox.Show("Error at loading " + SCENARIO_FILE+" file. "+e.Message, "Configuration Error", MessageBoxButtons.OK);
                Application.Exit();
                Environment.Exit(0);
                //App.Current;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            handleNewParticipant();
        }

        /// <summary>
        /// New participant
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simulNewParticipantMenuItem_Click(object sender, EventArgs e)
        {
            handleNewParticipant();
        }

        private void simulResultMenuItem_Click(object sender, EventArgs e)
        {
            FormResult formResult = new FormResult(_trials);
            formResult.Visible = true;
            formResult.MdiParent = this;
            //formResult.WindowState = FormWindowState.Maximized;
        }

        private void systemConfigurationMenuItem_Click(object sender, EventArgs e)
        {
            FormConfig formConfig = new FormConfig();
            DialogResult res = formConfig.ShowDialog(this);
        }


        private void handleNewParticipant()
        {
            FormLogin formLogin = new FormLogin(this._scenarioCollection);
            formLogin.StartPosition = FormStartPosition.CenterParent;
            DialogResult res = formLogin.ShowDialog(this);
            if (res == DialogResult.Cancel)
            {
                Application.Exit();
            } else if (res == DialogResult.OK)
            {
                if (formLogin.isAdmin)
                {
                    adminMode(true);
                }
                else
                {
                    adminMode(false);

                    FormParticipant formParticipant = new FormParticipant(formLogin.getParticipantInfo());
                    formParticipant.StartPosition = FormStartPosition.CenterParent;
                    DialogResult res2 = formParticipant.ShowDialog(this);

                    if (res2 == DialogResult.OK)
                    {
                        bool showInstruction = true;
                        while (showInstruction)
                        {
                            // Show the instructions
                            string[] instFiles = { AppContext.getInstance().getInstructionFilePath("instruction.rtf") };
                            RichTextMessage instruction = new RichTextMessage(instFiles);
                            instruction.StartPosition = FormStartPosition.CenterParent;
                            instruction.Text = "Instructions";
                            instruction.ShowDialog(this);

                            DialogResult hasQuestion = MessageBox.Show(this, "Do you have any questions for the experimenter?", "Question", MessageBoxButtons.YesNo);
                            if (hasQuestion == System.Windows.Forms.DialogResult.No)
                                showInstruction = false;
                        }

                        FormEventsGrid formEvents = new FormEventsGrid(this, _scenarioCollection.getScenarioSequence(formLogin.getSelectedScenarioSequene()), _trials);
                        _formEventsList.Add(formEvents);
                        formEvents.Text = "[Event] User: " + formParticipant.getParticipantInfo().id;
                        formEvents.ControlBox = true;
                        formEvents.Visible = true;
                        formEvents.MdiParent = this;
                        formEvents.WindowState = FormWindowState.Maximized;
                        formEvents.setParticipantInfo(formParticipant.getParticipantInfo());

                        // Insert the demographics to the database
                        _participantDao.insertOrUpdate(formParticipant.getParticipantInfo());
                    }
                }
            }
        }

        public void adminMode(bool enable)
        {
            this.mainMenu.Enabled = enable;
            this.ControlBox = enable;

            foreach (Form formEvents in _formEventsList)
            {
                formEvents.ControlBox = enable;
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();

        }
    }
}
